package com.visionork.android.tai.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

import com.visionork.android.tai.model.adapter.EpisodeAdapter;
import com.visionork.android.tai.model.adapter.TaiAdapterBase;

public class Program implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String title;
	private String urlLink;
	private String meta;
	private boolean favorite;
	private int programType;
	private TaiAdapterBase dataAdapter;

	private final ArrayList<Episode> episodes;

	public Program() {
		episodes = new ArrayList<Episode>();
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getTitle() {
		return title;
	}

	public void setUrlLink(String urlLink) {
		this.urlLink = urlLink;
	}

	public String getUrlLink() {
		return urlLink;
	}

	public void setFavorite(boolean favorite) {
		this.favorite = favorite;
	}

	public boolean isFavorite() {
		return favorite;
	}

	public ArrayList<Episode> getEpisodesRef() {
		return episodes;
	}

	public ArrayList<Episode> getEpisodes() {
		return getEpisodes(false);
	}

	public ArrayList<Episode> getEpisodes(boolean useCache) {
		if (!useCache) {
			@SuppressWarnings("unchecked")
			Collection<? extends Episode> data = (Collection<? extends Episode>) getDataAdapter()
					.getData();
			mergeData(data);
		}
		return episodes;
	}

	public void setMeta(String meta) {
		this.meta = meta;
	}

	public String getMeta() {
		return meta;
	}

	@Override
	public boolean equals(Object obj) {
		return getUrlLink().equals(((Program) obj).getUrlLink());
	}

	private TaiAdapterBase getDataAdapter() {
		if (dataAdapter == null) {
			dataAdapter = new EpisodeAdapter(urlLink);
		}
		return dataAdapter;
	}

	protected void mergeData(
			Collection<? extends com.visionork.android.tai.model.Episode> data) {
		for (Episode epi : data) {
			if (!episodes.contains(epi)) {
				/* add new one */
				episodes.add(epi);
			} else {
				/* update old one */
				Episode existEpi = episodes.get(episodes.indexOf(epi));
				existEpi.setTitle(epi.getTitle());
			}
		}

		/* remove expired one */
		for (Episode epi : episodes) {
			if (!data.contains(epi)) {
				episodes.remove(epi);

			}
		}
	}

	public void setProgramType(int programType) {
		this.programType = programType;
	}

	public int getProgramType() {
		return programType;
	}

	public Episode getEpisodeByUrlLink(String urlLink) {
		if (episodes.size() == 0) {
			getEpisodes(false);
		}
		for (Episode epi : episodes) {
			if (epi.getUrlLink().equals(urlLink)) {
				return epi;
			}
		}
		return null;
	}
}
